package org.darkforest.ucenter.service.impl;

import org.darkforest.dao.mapper.AddressMapper;
import org.darkforest.model.Address;
import org.darkforest.model.AddressVo;
import org.darkforest.ucenter.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 
 * 项目名称         :bwmall-ucenter
 * 文件名           :AddressServiceImpl.java
 * 开发公司及作者    :陈超
 * 版本号及开发日期  :Rev. 1.00 (2015年2月22日)
 */
@Service
public class AddressServiceImpl implements AddressService {

	
	@Autowired
	private AddressMapper addressMapper;
	
	@Override
	public List<Address> getAddressList(Integer memberId) {
		return addressMapper.selectByMember(memberId);
	}

	@Override
	public int addressAdd(AddressVo vo) {
		if("1".equals(vo.getIsDefault())){
			addressMapper.updateCleanDefaultByMember(vo.getMemberId());
		}
		return addressMapper.insertSelective(vo);
	}

	@Override
	public void addressEdit(AddressVo vo) {
		if("1".equals(vo.getIsDefault())){
			addressMapper.updateCleanDefaultByMember(vo.getMemberId());
		}
		addressMapper.updateByPrimaryKeySelective(vo);
	}

	@Override
	public int getAddressCount(Integer memberId) {
		return addressMapper.getAddressCount(memberId);
	}

	@Override
	public AddressVo getAddressById(Integer addressId, Integer memberId) {
		AddressVo vo = addressMapper.selectByPrimaryKey(addressId);
		if(vo != null){
			return vo;
		}
		return null;
	}

	@Override
	public int delAddressById(Integer addressId, Integer memberId) {
		Map<String, Object> p = new HashMap<String, Object>();
		p.put("addressId", addressId);
		p.put("memberId", memberId);
		return addressMapper.deleteByMember(p);
		
	}

	/**
	 * 根据用户ID获取该用户默认收货地址 如果用户没有设置默认地址 则取地址库中的第一条数据作为默认地址
	 *
	 * @param userId
	 * @return
	 */

	public Address getUserDefaultAddressByUserId(Integer userId) {
		Address address = addressMapper.getUserDefaultAddressByUserId(userId);
		if(address==null){
			List<Address> addressList = addressMapper.selectByMember(userId);
			if(addressList.size()>=1){
				address = addressList.get(0);
			}
		}
		return address;
	}

}
